package com.lexoo.moyuoo;


import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.Toast;

import static android.content.ContentValues.TAG;

public class DownloadTestActivity extends Activity {
    private DownloadManager downloadManager;
    private SharedPreferences prefs;
    private static final String DL_ID = "downloadId";
    /** Called when the activity is first created. */
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onCreate(Bundle savedInstanceState) {

//           llqtj();//添加浏览器按钮
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
        prefs = PreferenceManager.getDefaultSharedPreferences(this);
    }

    interface PermissionGrant {
        void onPermissionGranted(int requestCode);
    }
    //权限申请


    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        unregisterReceiver(receiver);
    }


    private void checkPermission() {
        boolean jieguo =false;
        if (Build.VERSION.SDK_INT >= 23) {
            int write = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            int read = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
            if (write != PackageManager.PERMISSION_GRANTED || read != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 300);
            } else {
                String name = "CrashDirectory";
                File file1 = new File(Environment.getExternalStorageDirectory(), name);
                if (file1.mkdirs()) {
                    Log.i("wytings", "permission -------------> " + file1.getAbsolutePath());
                } else {
                    Log.i("wytings", "permission -------------fail to make file ");
                }
            }
        } else {
            Log.i("wytings", "------------- Build.VERSION.SDK_INT < 23 ------------");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 300) {
            Log.i("wytings", "--------------requestCode == 300->" + requestCode + "," + permissions.length + "," + grantResults.length);
        } else {
            Log.i("wytings", "--------------requestCode != 300->" + requestCode + "," + permissions + "," + grantResults);
        }
    }


    @SuppressLint("WrongConstant")
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onResume() {

        super.onResume();
        qx();
        llqtj();
        final Button button =findViewById(R.id.xiazaibtn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(DownloadTestActivity.this,"开始下载【墨域奇迹...】",3).show();
                // TODO Auto-generated method stub
                Log.d(TAG, "onClick: 按钮出问题");
                if (!prefs.contains(DL_ID)) {
                    button.setBackgroundColor(Color.GRAY);
                    String url = "http://120.79.29.157/package/moyumu2.apk";
                    //开始下载 
                    Uri resource = Uri.parse(encodeGB(url));
                    DownloadManager.Request request = new DownloadManager.Request(resource);
                    request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI);
                    request.setAllowedOverRoaming(false);
                    //设置文件类型
                    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
                    String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
                    request.setMimeType(mimeString);
                    //在通知栏中显示 
                    request.setShowRunningNotification(true);
                    request.setVisibleInDownloadsUi(true);
                    //sdcard的目录下的download文件夹
                    request.setDestinationInExternalPublicDir("/download/", "moyumu.apk");
                    request.setTitle("墨域奇迹开始下载...");
                    long id = downloadManager.enqueue(request);
                    //保存id 
                    prefs.edit().putLong(DL_ID, id).commit();
                } else {
                    //下载已经开始，检查状态
                    queryDownloadStatus();
                }
            }});
        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        // TODO Auto-generated method stub

    }
    @RequiresApi(api = Build.VERSION_CODES.M)
    void qx() {
        //判断是否有权限
        PackageManager pm = getPackageManager();
        boolean permission = (PackageManager.PERMISSION_GRANTED ==
                pm.checkPermission("android.permission.WRITE_EXTERNAL_STORAGE", "com.lexoo.moyuoo"));
        if (permission) {

            return;

        } else {
            try {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 300);
            } catch (Exception e) {
                Log.d(TAG, "qx: 申请出现问题");
                return;
            }
            try {
                qx();
            } catch (Exception e) {
                return;
            }
        }
    }

    public String encodeGB(String string) {
        //转换中文编码
        String split[] = string.split("/");
        for (int i = 1; i < split.length; i++) {
            try {
                split[i] = URLEncoder.encode(split[i], "GB2312");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            split[0] = split[0]+"/"+split[i];
        }
        split[0] = split[0].replaceAll("\\+", "%20");//处理空格
        return split[0];
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //这里可以取得下载的id，这样就可以知道哪个文件下载完成了。适用与多个下载任务的监听
            Log.v("intent", ""+intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0));
            queryDownloadStatus();
        }
    };

    private void queryDownloadStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(prefs.getLong(DL_ID, 0));
        Cursor c = downloadManager.query(query);
        if(c.moveToFirst()) {
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch(status) {
                case DownloadManager.STATUS_PAUSED:
                    Log.v("down", "STATUS_PAUSED");
                case DownloadManager.STATUS_PENDING:
                    Log.v("down", "STATUS_PENDING");
                case DownloadManager.STATUS_RUNNING:
                    //正在下载，不做任何事情
                    Log.v("down", "STATUS_RUNNING");
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    //完成
                    Log.v("down", "下载完成");
                    break;
                case DownloadManager.STATUS_FAILED:
                    //清除已下载的内容，重新下载
                    Log.v("down", "STATUS_FAILED");
                    downloadManager.remove(prefs.getLong(DL_ID, 0));
                    prefs.edit().clear().commit();
                    break;
            }
        }
    }

    //浏览器按键添加
    void llqtj(){
        final Button button2 = (Button) findViewById(R.id.liulanqibt);
        button2.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("WrongConstant")
            @Override
            public void onClick(View view) {
                button2.setBackgroundColor(Color.GRAY);
                Toast.makeText(DownloadTestActivity.this, "浏览器下载...", 3).show();
                //打开浏览器意图
                Uri uri = Uri.parse("http://120.79.29.157:83/package/moyumu2.apk");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });




    }




}